package com.bigfans.framework.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

public class HttpUtils {
	
	public static void httpDownload(String url, File outFile) {
		// 创建HttpClientBuilder
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		HttpGet request = new HttpGet(url);
		InputStream is = null;
		try {
			// 执行get请求
			HttpResponse httpResponse = closeableHttpClient.execute(request);
			// 获取响应消息实体
			HttpEntity entity = httpResponse.getEntity();
			// 判断响应实体是否为空
			if (entity != null) {
				is = entity.getContent();
				File parentFile = outFile.getParentFile();
				if (!parentFile.exists()) {
					parentFile.mkdirs();
				}
				IOUtils.copyToFile(is, outFile);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(closeableHttpClient);
		}
	}

}
